<?php
class Admin_UserController extends Zendvn_Controller_Action
{
	public function init()
	{
		$template_path=TEMPLATE_PATH."/admin/system";
		$this->loadTemplate($template_path);
		
	}
	public function indexAction()
	{
		
		$user = new Admin_Model_User();
		
		 $this->view->user=($user->getUser()->toArray());
		 
	}

	public function loginAction() {
		
		$template_path=TEMPLATE_PATH."/admin/system";
		$this->loadTemplate($template_path,'template1.ini');
		$form=new Admin_Form_User();
		$this->view->form=$form;
		$this->view->headTitle()->append("-Dang Nhap");
		
	
	    if ($this->_request->isPost()) {
	    	$formdata= $this->_request->getPost();
	    	if($form->isValid($formdata))
	    	{
	
	        //1.Goi ket noi voi Zend Db
	        $db = Zend_Registry::get('connectDb');
	        //$db = Zend_Db::factory($dbOption['adapter'],$dbOption['params']);
	        //2. Khoi tao Zend Autho
	        $auth = Zend_Auth::getInstance ();
	
	        //3. Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
	        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
	        $authAdapter->setTableName('user')
	                ->setIdentityColumn('UserName')
	                ->setCredentialColumn('Password');
	              
	
	        //4. Lay gia tri duoc gui qua tu FORM
	        $uname = $this->_request->getParam('username');
	        $paswd = $this->_request->getParam('password');
			
	        //5. Dua vao so sanh voi du lieu khai bao o muc 3
	        $authAdapter->setIdentity($uname);
	        $authAdapter->setCredential($paswd);
	
	        //6. Kiem tra trang thai cua user neu Groupid = 1 moi duoc login
	        $select = $authAdapter->getDbSelect();
	        $select->where('Groupid= 1');
	
	        //7. Lay ket qua truy van
	        $result = $auth->authenticate($authAdapter);
	        $flag = false;
	     
	        if ($result->isValid()) {
	  
	            //8. Lay nhung du lieu can thiet trong bang users neu login thanh cong				
	            $data = $authAdapter->getResultRowObject(null, array('Password'));
			
	            //9. Luu  nhung du lieu cua member vao session
	            $auth->getStorage()->write($data);
	            $flag = true;
	        }
	        if ($flag == true) {
	           $this->_redirect('admin/index');
	        }
	    	}
	    }
	}

	public function logoutAction() {
	    $auth = Zend_Auth::getInstance();
	    $auth->clearIdentity();
	    $this->_redirect('admin/index');
	    
	    
	}
	
	
}